<template>
	<view class="">

		<button open-type="getUserInfo" lang="zh_CN" @getuserinfo="onGotUserInfo">获取用户信息</button>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				appid: "wx11661ad67d87437e",
				secret: "51f1e79e8783db55cc2ce801f9599fae"
			};
		},
		mounted() {

		},
		methods: {
			onGotUserInfo(e) {
				// 获取用户信息
				uni.login({
					provider: 'weixin',
					success: (res) => {
						console.log(res);

						const self = this;
						var appid = self.appid; //这里是我的appid，需要改成你自己的
						var secret = self.secret; //密钥也要改成你自己的
						var openid = '';
						var url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' + appid + '&secret=' + secret + '&js_code=' +
							res.code + '&grant_type=authorization_code';
						uni.request({
							url: url,
							data: {},
							method: 'GET',
							success: (resrequest) => {
								var obj = {};
								obj.openid = resrequest.data.openid;
								console.log('openid: ' + resrequest.data.openid);
								self.$u.vuex('vuex_openid', resrequest.data.openid)
								obj.expires_in = Date.now() + resrequest.data.expires_in;


								// 获取用户信息

								uni.getUserInfo({
									provider: 'weixin',
									success: (infoRes) => {
										console.log(infoRes);
										this.$u.vuex('vuex_userinfo', infoRes.userInfo);
										let userobj = {}
										userobj.openid = obj.openid
										userobj.expires_in = obj.expires_in
										userobj.userinfo = infoRes.userInfo
										console.log(userobj)
										uniCloud.callFunction({
											name: 'adduser',
											data: userobj
										}).then((res) => {
											console.log(res)
										}).catch((err) => {
										})
									},
								});




							}
						});



						uni.reLaunch({
							url: '../index/index'
						});
					}
				});
			},
			// getOpenId() {
			// 	const self = this;
			// 	uni.login({
			// 		success: function(res) {
			// 			if (res.code) {
			// 				uni.getUserInfo({
			// 					success: function(res) {
			// 						console.log('存在code');
			// 					}
			// 				});
			// 				var appid = self.appid; //这里是我的appid，需要改成你自己的
			// 				var secret = self.secret; //密钥也要改成你自己的
			// 				var openid = '';
			// 				var url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' + appid + '&secret=' + secret + '&js_code=' + res.code + '&grant_type=authorization_code';
			// 				uni.request({
			// 					url: url,
			// 					data: {},
			// 					method: 'GET',
			// 					success: function(res) {
			// 						var obj = {};
			// 						obj.openid = res.data.openid;
			// 						console.log('openid: ' + res.data.openid);
			// 						obj.expires_in = Date.now() + res.data.expires_in;
			// 					}
			// 				});
			// 			} else {
			// 				console.log('获取用户登录态失败！' + res.errMsg);
			// 			}
			// 		}
			// 	});
			// }
		}
	}
</script>

<style scoped lang="less">

</style>
